Archive | 7:53 am

PHP: Method chaining using object oriented programming

27 May

While in my previous article I discussed some of the nice thing of object oriented programming. Inheritance –creating sub classes from inheriting parent, contain all the attributes of the parent class plus its own. Polymorphism, means different form, like overloading and overriding methods and dynamic binding- deciding which class in the inheritance tree should be called on runtime, are techniques that give great benefits to programmers.

In this article I am going to show you a simple but very useful trick while using “this” keyword for method chaining. “this” when use in the class refer to the same class.

Consider the following example.

class Person {

protected $_name;

protected $_age;

protected $_gender;

public function setName($name) {

$this->_name  = $name;

}

public function getName() {

return $this->_name;

}

public function setAge ($age) {

$this->_name  = $age;

}

public function getAge() {

return $this->_age;

}

public function setGender($gender) {

$this->_gender  = $gender;

}

public function getGender() {

return $this->_gender;

}

}

While in object oriented programming it’s always a good practice to define getter and setters.

To create an object of the above class and define person properties, we will need to write the following code.

$person = new Person();

$person->setName(“person_name”);

$person->setAge(24);

$person->setGender(“male”);

And now If you want to get these values, write

$person->getName();

$person->getAge();

$person->getGender();

Well, if you want to set values using a single statement, you will need a code similar to this.

$this->setName(‘person_name’)->setAge(24)->setGender(“male”);

To achieve this, you will need to write the following statement in all your setters.

public function setName($name) {

$this->_name  = $name;

return $this;

}

The only thing we need here is “return $this”. This statement return a reference to the same object.

Place this statement in your setAge() and setGender(), and now you can write

$this->setName(‘person_name’)->setAge(24)->setGender(“male”);

for setting all the three properties